﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Kinect;

using System.Runtime.InteropServices;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

using System.Collections.ObjectModel;
using System.Runtime.Remoting.Messaging;
using System.ComponentModel;

///
/// 8/21/2012 - Jfarro - Created
///
namespace KSASupport
{    
    /// <summary>
    /// Responsible for all management of the Kinect Sensors and depth events
    /// </summary>
    public class KinectManager
    {
        private KinectSensor kinectSensor;
        /// <summary>
        /// a handle to a Kinect sensor
        /// </summary>
        public KinectSensor KinectSensor
        {
            get { return kinectSensor; }
            set { kinectSensor = value; }
        }
        
        /// <summary>
        /// Instantiates a new Kinectmanager
        /// </summary>
        public KinectManager()
        {
            kinectSensor = null;
        }


        /// <summary>
        /// Call this to initialize each instance of the engine. For each Kinect, this engine can
        /// be instantiated separately for different scenarios.
        /// </summary>
        /// <param name="KinectSensorToUse"></param>
        public void Initialize(int KinectSensorToUse,DepthImageFormat format,DepthRange range)
        {
            try
            {
                kinectSensor = KinectSensor.KinectSensors[KinectSensorToUse];
                kinectSensor.DepthStream.Range = range;
                kinectSensor.DepthStream.Enable(format);
            }
            catch (IndexOutOfRangeException)
            {
                throw new Exception("Kinect was not found!");
            }
        }
        /// <summary>
        /// Tries to set the Kinect to near mode
        /// </summary>
        /// <returns>True if successful, False if it fails</returns>
        public bool SetDepthRange(DepthRange range)
        {
            try
            {
                kinectSensor.DepthStream.Range = range;
                return true;
            }
            catch (Exception)
            {
                kinectSensor.DepthStream.Range = DepthRange.Default;
                return false;
            }
        }

        public void SetDepthImageFormat(DepthImageFormat format)
        {
            kinectSensor.DepthStream.Disable();            
            kinectSensor.DepthStream.Enable(format);
        }

        public KinectStatus GetKinectStatus()
        {
            return kinectSensor.Status;
        }
        
        public void Uninitialize()
        {
            kinectSensor.Stop();
        }
    }
}
